$(document).ready(function(){
   $('#advancedSearch').click(function(){
      var target = $('#checkboxsearch');
         if(target.is(':hidden')) {
            target.show();
            $(this).addClass('lowsearch');
            var pwrapheight = $(".highsearch_wrap").height()+66;
            $(".hr_manegeinterview_set").css("paddingTop",pwrapheight+"px");
         } else {
            target.hide();
            $(this).removeClass('lowsearch');
            $(".hr_manegeinterview_set").css("paddingTop","40px");
         }
   });

   $('#checkboxsearch').on('click', '.click_slideup', function(){
      $('#advancedSearch').trigger('click');
   });

   $("#hr_inner_navigate #sequence_time a").click(function(){
      var orderby = $(this).data('orderby'); 
      var orderdir = $(this).data('orderdir');
      $.ajax({
         type: "POST",
         url: OC.filePath('calendar', 'ajax', 'sortlist.php'),
         data: {orderby: orderby, orderdir: orderdir},
         dataType: 'json',
         success: function(result){
            var url = window.location.href,
            ts = jQuery.now(),
            ret = url.replace( /([?&])_=[^&]*/, "$1_=" + ts );
            window.location = ret + ( ( ret === url ) ? ( /\?/.test(url ) ? "&" : "?" ) + "_=" + ts : "" );    
         }
       });
   });

   $("#selectearly #selectall").click(function(){
      var show_prev = $("#selectall").val();
      $.ajax({
         type: "POST",
         url: OC.filePath('calendar', 'ajax', 'selectlist.php'),
         data: {show_prev: show_prev},
         dataType: 'json',
         success: function(result){
            var url = window.location.href,
            ts = jQuery.now(),
            ret = url.replace( /([?&])_=[^&]*/, "$1_=" + ts );
            window.location = ret + ( ( ret === url ) ? ( /\?/.test(url ) ? "&" : "?" ) + "_=" + ts : "" );    
         }
      });
   })

   $('#joblinks').on('click', '.last_lookmore', function(){
      $.metadata.setType('attr', 'data');
      var data = $('#resumesearch_wrap').metadata();
      var jobid = data.jobid;
      var list_url = joblist_url;
      var searchurl = data.searchurl;

      if(jobid > 0) {
         var list_url = getUrlQuery(list_url, "jobid="+jobid);
      }

      $(this).jobSelect({
         title: '选择职位',
         listurl: list_url,
         searchurl: searchurl
      });
   });

   $("#interviewlists a").on("click",function(){
      var target = $(this);
      $.metadata.setType('attr', 'data');
      var data = $(this).metadata();
      var jobseekid = data.jobseekid;
      var objectid = data.objectid;
      var jobid = data.jobid;
      $.ajax({
          type: "GET",
          url: OC.filePath('calendar', 'ajax', 'interviewlist.php'),
          cache: false, 
          beforeSend: function(xhr, settings) {
             showLoading(target, settings, null, {button: true});
          },
          data: {jobid: jobid,jobseekid: jobseekid,objectid: objectid},
          dataType: 'html',
          success: function(result){
             $("#preview_holder").html(result);
             $("#preview_holder").show().position({
                 my: "left top+10",
                 at: "left-8 bottom",
                 of: target,
                 collision:"none"
              });
          }
        });
   });

   $("#interviewfeedback a").on("click",function(){
      var target = $(this);
      $.metadata.setType('attr', 'data');
      var data = $(this).metadata();
      var jobseekid = data.jobseekid;
      var jobid = data.jobid;
      $.ajax({
          type: "GET",
          url: OC.filePath('calendar', 'ajax', 'interviewfeedback.php'),
          beforeSend: function(xhr, settings) {
             showLoading(target, settings, null, {button: true});
          },
          data: {jobid:jobid,jobseekid: jobseekid},
          dataType: 'html',
          success: function(result){
           $("#feedback_dialog").html(result);
              $("#feedback_dialog").show().position({
                  my: "left top+10",
                  at: "left-8 bottom",
                  of: target,
                  collision:"none"
               });
          }
      });
   });

   $("#dropdownmenu a").on("click",function(){
      var target = $(this);
      $.metadata.setType('attr', 'data');
      var data = $(this).metadata();
      var jobid = data.jobid;
      var resultid = data.resultid;
      var objectid = data.objectid;
      var jobseekerid = data.jobseekerid;
      var jobseekername = data.jobseekername;
      var jobtitle = data.jobtitle;
      var round = data.round;
      var statusid = data.statusid;
      var offerstatus = data.offerstatus;
      var validemail = data.validemail;
      var type = 0;
      var canceled = data.canceled;
      var pagetype = $('#cancel_showdialog').data('pagetype');
      //resultid 3:复试
      if(resultid == 3){
         $('#event_modal').load(OC.filePath('calendar', 'ajax/event', 'new.form.php'), {jobseekerid:jobseekerid, jobseekername:jobseekername, jobid:jobid, jobtitle:jobtitle,round:round,objectid:objectid,type:type,validemail:validemail}, function(){
            $('label.checkbox.gray').tooltip();
            setTimeout(function () {
               if(!$('#event_modal #sendemail').is(':checked')) {
                  if(!$('#event_modal #sendsms').is(':checked') && $('#event_modal #sendsms').attr("disabled") != "disabled") {
                     showMessagePanel('简历缺少Email信息，请设置发送短信', $("#event_modal #sendsms").parent("label"), true, {placement:'right', timeout:3000});
                  }
               }
            }, 500);
            //upload reinterview attachment
            jQuery('#uploadcalendarform').fileUploadUIX({
               allowOfficeTypes: true,
               keepList: true,
               autoUpload: true,
               maxFileSize: 4*1024*1024,
               onError:function(response){
                  $("#uploadcalendartable tr:last").remove();
                  $(".errors").show().html(' <div class="error">' + response +'</div>');;
                  $(".errors").fadeOut(3000);
                  return false;
               },
               onCompleteAll: function(list) {
                  jQuery.each(list, function(i, o) {
                     var handler = o.slice(-1)[0];
                     if(handler.response.error) {
                        $(".errors").show().html(' <div class="error">' + handler.response.error +'</div>');
                        $(".errors").fadeOut(3000);
                     }else{
                        $("#fileshowarea").show().html("<span class="+handler.response.attachid+" fileshoweach <em>"+handler.response.name+"</em> <a href='javascript:;' id='del_name' data = {'attachid':'"+handler.response.attachid+"','attachname':'"+handler.response.name+"'}>删除</a></br></span>");
                        $("#attachment").val(handler.response.attachid);
                        $(".errors").show().html(' <div class="success">成功上传</div>');
                        if(!$('#calendar_att_div .inviteselectmenubox').hasClass("dropdown")){
                           $('#calendar_att_div .inviteselectmenubox').addClass("dropdown");
                           $('#calendar_att_div .inviteselectmenubox #invs_two').attr('data-toggle','dropdown');
                        }
                        $(".history_list").append("<a  id='choosehistory' data={'attachname':'"+handler.response.name+"','attachid':'"+handler.response.attachid+"'} href='javascript:;' class='this"+handler.response.attachid+"'> <span style='display:inline;'>"+handler.response.name+"</span><i data={'attachid':'"+handler.response.attachid+"','attachname':'"+handler.response.name+"'} id='history_atachment' class='delete'></i></a>");
                        $(".errors").fadeOut(3000);
                        $("#uploadcalendartable tr:last").remove();
                     }    
                  });
               }
            });
                        
            $("#event_form").validate({
               rules: {
                  contact_phone: {required:true,phone: true},
                  address: {required: true},
                  contact: {notalldigits:true}
               },
               messages: {
                  contact_phone: {
                     required: "请输入联系电话",
                     phone: "请输入正确的联系电话"
                  },
                  address: {
                     required: "请输入面试地点"
                  },
                  contact: {
                     notalldigits:"联系人不能为纯数字"
                  }
               },
               success:function(label){
                  var prev = $("#event_modal #errorbox").data("element");
                  if ( label.attr("for") == prev && (prev == "contact_phone" || prev == "address" || prev == "contact") ) {
                     $("#event_modal #errorbox").data("element", "").html("").hide();
                  }
               },
               errorPlacement:function(error,element) {
                  var validator = $("#event_modal #event_form").data("validator");
                  if( element.attr("name") == "contact_phone" || element.attr("name") == "address" || element.attr("name") == "contact" ) {
                     var prev = $("#event_modal #errorbox").data("element");
                     if(prev) {
                        if($.grep(validator.errorList, function(error, i) {      
                           if($(error.element).attr("name") == prev) 
                              return true;
                           return false;
                        }).length > 0)
                           return;
                     }
                     if(error.text()) {
                        $("#event_modal #errorbox").data("element", element.attr("name")).jobUtil('showError', error.text());
                     }
                  } else {
                     error.insertAfter(element);
                  }
               },
               submitHandler: function(form) {
                  if($("#event_modal #event_form #submitNewEvent").hasClass("ppp_graybtn")) {
                     return false;
                  }
            
                  $("#event_form").ajaxSubmit({
                     type: 'post',
                     dataType: "json",
                     beforeSubmit: function(data, form, options) {
                        if (!showLoading("#submitNewEvent", options, null, {button:true}))
                           return false;
                        $("#errorbox").hide();
                     },
                     success: function(data) {
                        try {
                           var retmsg = data;
                           if (retmsg.error) {
                              $("#errorbox").jobUtil('showError', retmsg.error);
                           }
                           else if(retmsg.success) {
                              $('#event_modal').modal('hide');
                              var scrolltop = $(window).scrollTop();
                              $("#notify_showdialog").css({top:scrolltop+200}).modal();
                              $('#notify_showdialog').on('hidden',function(){
                                 window.location.reload();
                              });
                           }
                        } catch(e) {
                           return false;
                        }
                     }
                  });
               }
            });
            var scrolltop = $(window).scrollTop();
            $("#event_modal").css({top:scrolltop+75}).modal("show");
            if($.isFunction($.fn.placeholder)) {
               $("input, textarea", "#event_modal").placeholder();
            }
         });
      }
      else{
         //resultid = 5:cancel, canceled = 0 :have not sended cancel email
         if(resultid == 5 && canceled == 0){
            showConfirmDialog('<div class="ciw_words"><i></i> 取消面试将会发送通知给面试官和应聘者，您确认要取消面试吗？</div>',function() {
               $.ajax({
                  type: "POST",
                  url: setinterviewresult,
                  data: {jobid: jobid, resultid: resultid, objectid: objectid,jobseekerid:jobseekerid,statusid:statusid},
                  dataType: 'json',
                  success: function(data){
                     if(data.success){
                        $("#cancel_showdialog").hide();
                        $('#invite'+objectid+' #dropdownmenu a').parent().parent().parent().nextAll().hide();
                        $("#resultlists"+objectid).text('已取消');
                        // pagetype 1:resume 2:calendar
                        if(pagetype == 1){
                           $("#invite"+objectid).append('<div class="invite_interviewbtn pull-right" id="invite_interviewbtn"><a href="javascript:;" data-eventid="'+objectid+'" data-resultid="5" id="editEvent">安排面试</a></div>');
                        }
                        window.location.reload();
                     }
                     else {
                        showMessagePanel(data.error, target.closest('.dropdown'), true, {placement:'right'});
                     }
                  }
               });
            });
         }else{
            $.ajax({
               type: "POST",
               url: setinterviewresult,
               data: {jobid: jobid, resultid: resultid, objectid: objectid,jobseekerid:jobseekerid,statusid:statusid},
               dataType: 'json',
               success: function(data){
                  if(data.success){
                     $(target).parent().parent().parent().nextAll().hide();
                     $("#resultlists"+objectid).text(target.data('showtext')? target.data('showtext'): target.text());
                     //resultid 1:录用 2：不录用
                     if(resultid == 1 ){
                        if(offerstatus >0 ){
                           //这边用来显示（已完成）发offer，offer状态下拉框
                           $('#invite'+objectid+' #sendoffer').parent().show().prev().show();
                           $('#invite'+objectid+' #sendoffer').parent().next().show().next().show();
                           //这边用来显示入职的流程
                           if($('#offerresulttext'+objectid).text() == '接受offer'){
                              $('#invite'+objectid+' #entrystat').parent().parent().show().prev().show();
                           }
                        }else{
                           //这边用来显示（未完成）发offer
                           $('#invite'+objectid+' #sendoffer').parent().show().prev().show();
                           $('#invite'+objectid+' #sendoffer').trigger("click");
                        }
                     }
                     if(resultid == 2 ){
                        var jobseekerlink = $("#span"+jobseekerid+" #senddecline");
                        jobseekerlink.parent().show().prev().show();
                        if( !jobseekerlink.find("i").hasClass("ok") )　{
                           //这边用来显示发不录用通知
                           jobseekerlink.trigger("click");
                        }
                     }
                     //pagetype 1:resume 2:calendar
                     if(pagetype == 1 && offerstatus == 0){
                        //resultid 5:取消 3:复试
                        if(resultid == 5 || resultid == 3){
                           $("#invite"+objectid).append('<div class="invite_interviewbtn pull-right" id="invite_interviewbtn"><a href="javascript:;" data-eventid="'+objectid+'" data-resultid="5" id="editEvent">安排面试</a></div>');  
                        }else{
                           $("#invite"+objectid).append('<a id="cancelEvent" href="javascript:;" data="{jobseekid:'+jobseekerid+',jobid:'+jobid+',eventid:'+objectid+'}" eventtype="VEVENT" class="pull-right">取消</a><em class="pull-right">&nbsp;&nbsp;|&nbsp;&nbsp;</em><a id="editEvent" data-resultid="'+resultid+'" data-eventid="'+objectid+'" href="javascript:;" class="pull-right">修改</a>');
                        }
                     }
                  }
                  else {
                     showMessagePanel(data.error, target.closest('.dropdown'), true, {placement:'right'});
                  }
               }
            });
         }
      }
   });
   
   $(document).on("click","#offerstat a",function(){
      var target = $(this);
      $.metadata.setType('attr', 'data');
      var data = $(this).metadata();
      var objectid = data.objectid;
      var jobseekerid = data.jobseekid;
      var offerstat = data.offerstat;
      var statusid = data.statusid;
      var jobid = data.jobid;
      $.ajax({
         type: "POST",
         url: setofferresult,
         data: {objectid:objectid, jobseekerid: jobseekerid, offerstat: offerstat, statusid: statusid, jobid: jobid},
         dataType: 'json',
         success: function(data){
            var retmsg = data;
            if (retmsg.error) {
               return false
            }
            else if(retmsg.success) {
               $("#offerresulttext"+objectid).text(target.text());
               // offerstart 320：接受offer
               if( statusid == 320){
                  $('#invite'+objectid+' #entrystat').parent().parent().show().prev().show();
               }else{
                  $('#invite'+objectid+' #entrystat').parent().parent().hide().prev().hide();
               }
            }
         }
      });
   });

   $(document).on("click","#senddecline",function(){
      var target = $(this);
      $.metadata.setType('attr', 'data');
      var data = $(this).metadata();
      var objectid = data.objectid;
      var jobseekid = data.jobseekid;
      var jobid = data.jobid;
      $.ajax({
          type: "GET",
          url: OC.filePath('calendar', 'ajax', 'senddecline.php'),
          data: {objectid: objectid,jobseekid: jobseekid,jobid: jobid},
          dataType: 'html',
          success: function(result){
             var scrolltop = $(window).scrollTop();
             $("#interviewfailed").html(result).css({top:scrolltop+75}).modal();
          }
       });
   });

   $(document).on('click','#interviewfailed #declinesend',function(){
      var jobseekerid = $('#interviewfailed #jobseekerid').val();
      var jobseekername = $('#interviewfailed #jobseekername').val();
      var objectid = $('#interviewfailed #objectid').val();
      var jobid = $('#jobid').val();
      $.ajax({
         type: "POST",
         url: declinesend,
         data: {jobseekerid: jobseekerid,jobseekername:jobseekername,objectid:objectid,jobid:jobid},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            showLoading('#declinesend', settings, null, {button: true});
         },
         success: function(data) {
            try {
               var retmsg = data;
               if (retmsg.error) {
                  $('#interviewfailed #senderror').jobUtil("showError", retmsg.error);
               }
               else if(retmsg.success) {
                  $('#span'+jobseekerid+' #senddecline').removeAttr("id");
                  $('#span'+jobseekerid+' a i').removeClass('finish notok').addClass('finish ok');
                  $('#interviewfailed').modal('hide');
                  showStatusDialog('面试结果通知发送成功！');
               }
            } catch(e) {
               return false;
            }
         }
      });
   })

   $(document).on('click','#preview_holder #showdetails',function(){
      var target = $(this);
      $.metadata.setType('attr', 'data');
      var data = $(this).metadata();
      var num = data.num;
      var objectid = data.objectid;
      if($('#detail'+num+'').css("display") != "none") {
         $('#detail'+num+'').hide(); 
         return; 
      }
      if($('#detail'+num+'').html().length > 0) {
         $('#detail'+num+'').show();
      }
      else {
         $.ajax({
            type: "GET",
            url: OC.filePath('calendar', 'ajax', 'getinterviewdetails.php'),
            data: {objectid: objectid},
            dataType: 'html',
            beforeSend: function(xhr, settings) {
               showLoading(target, settings, null, {button: true});
            },
            success: function(result){
               $('#detail'+num+'').html(result).fadeIn();
            }
         });
      }
   })

   $(document).on('click','#feedbackform #submitfeedback',function(){
      var objectid = $("input[name=objectid]").val();
      var uid = $("input[name=uid]").val();
      $.ajax({
         type: "POST",
         url: setinterviewfeedback,
         data: $( "#feedbackform" ).serialize(),
            dataType: 'json',
            success: function(data) {
               try {
                  var retmsg = data;
                  if (retmsg.error) {
                     $('#feedbackform #error').jobUtil('showError', retmsg.error);
                  }
                  else if(retmsg.success) {
                     $('#feedbackform #error').jobUtil('showSuccess', retmsg.success);
                     window.location = feedbackpreview+'?id='+objectid+"&w="+uid;
                  }
               } catch(e) {
                  return false;
               }
            }
      });
   });

   $('#feedback_dialog').on('click','#remind',function(){
      var target = $(this);
      var data = target.metadata();
      var objectid = data.objectid;
      var jobid = data.jobid;
      $.ajax({
         type: "POST",
         url: interviewfeedbackremind,
         data: {objectid:objectid,jobid:jobid},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            showLoading(target, settings, null, {button:true});
         },
         success: function(data) {
            try {
               var retmsg = data;
               if (retmsg.error) {
                  showMessagePanel(retmsg.error, target, true, {placement:'right'});
               }
               else if(retmsg.success) {
                  var html = '<span>'+retmsg.success+'</span>';
                  $(target).get(0).outerHTML = html;
               }
            } catch(e) {
               return false;
            }
         }
      })
   });
   
   $('#feedbackform .feedbackform_table').on('click','tr td',function(){
      $(this).addClass("selected_td").siblings().removeClass("selected_td");
      $(this).find("input:radio").prop("checked", true).siblings().find("input:radio").prop("checked", false);
   });

   $(document).on("click","#entrystat a",function(){
      var target = $(this);
      $.metadata.setType('attr', 'data');
      var data = $(this).metadata();
      var objectid = data.objectid;
      var jobseekerid = data.jobseekid;
      var entrystat = data.entrystat;
      var jobid = data.jobid;
      var statusid = data.statusid;
      $.ajax({
         type: "POST",
         url: setentryresult,
         data: {objectid:objectid, jobseekerid: jobseekerid, entrystat: entrystat, jobid: jobid, statusid: statusid},
         dataType: 'json',
         success: function(data){
            var retmsg = data;
            if (retmsg.error) {
               return false
            }
            else if(retmsg.success) {
               $("#entryresulttext"+objectid).text(target.text());
            }
         }
      });
   });

   $("#if_absent").on("click", function(event) {
      $("#error").html("");
      if($(this).hasClass("absent_yes")) {
         $(this).removeClass("absent_yes").addClass("absent_no");
         $("#absent").val("0");
         $(".feedbackform_comdiv.clearfix").show();
         $(".feedbackform_table").show();
      } else if($(this).hasClass("absent_no")) {
         $("input:radio[name='suggestion']").prop("checked",false);
         $(this).removeClass("absent_no").addClass("absent_yes");
         $("#absent").val("1");
         $(".feedbackform_comdiv.clearfix").hide();
         $(".feedbackform_table").hide();
      } else {
         return;
      }
   });
})
